<?php
class emailTask extends sfBaseTask {

  const CONTENT_TYPE_PLAIN          = 'text/plain';
  const CONTENT_TYPE_HTML           = 'text/html';

  const STATUS_PENDING              = 0;
  const STATUS_SENT                 = 1;
  const STATUS_FAILED               = 9;

  protected function configure() {
    $this->namespace = 'stn';
    $this->name = 'email';
    $this->addOption('env', null, sfCommandOption::PARAMETER_OPTIONAL, 'Changes the environment this task is run in', 'dev');
    $this->addOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'Changes the application this task is run in', 'frontend');
  }

  protected function execute($arguments = array(), $options = array()) {
    $configuration = ProjectConfiguration::getApplicationConfiguration($options['application'], $options['env'], false);
    sfContext::createInstance($configuration);
    $databaseManager = new sfDatabaseManager($configuration);
    sfProjectConfiguration::getActive()->loadHelpers('Partial');

    $emailList = EMAILTable::getInstance()->getUnsentEmails(10);

    foreach($emailList as $email) {
      $sendSuccess = true;

      $phpMailer = new PHPMailer();
      $phpMailer->Host = sfConfig::get('app_email_host');
      if ((bool)sfConfig::get('app_email_is_smtp') === true) {
        $phpMailer->IsSMTP();
        $phpMailer->SMTPAuth = true;
      }
      $phpMailer->Port = sfConfig::get('app_email_port');
      $phpMailer->Timeout = 60;
      $phpMailer->CharSet = 'UTF-8';
      $phpMailer->Username = sfConfig::get('app_email_username');
      $phpMailer->Password = sfConfig::get('app_email_password');

      if ($email->getEmailTo() != null) {
        $phpMailer->AddAddress($email->getEmailTo());
      } else {
        continue;
      }

      if ($email->getEmailCc() != null) {
        $emailCc = explode(',', $email->getEmailCc());
        foreach ($emailCc as $e) {
          $phpMailer->AddCC(trim($e));
        }
      }

      if ($email->getEmailBcc() != null) {
        $emailBcc = explode(',', $email->getEmailBcc());
        foreach ($emailBcc as $e) {
          $phpMailer->AddBCC(trim($e));
        }
      }

      if ($email->getEmailFrom() != null) {
        $phpMailer->From = $email->getEmailFrom();
      } else {
        continue;
      }

      if ($email->getSenderName() != null) {
        $phpMailer->FromName = $email->getSenderName();
      }

      if ($email->getEmailReplyto() != null) {
        $phpMailer->AddReplyTo($email->getEmailReplyto());
      } else {
        $phpMailer->AddReplyTo($email->getEmailFrom());
      }

      if ($email->getSubject() != null) {
        $phpMailer->Subject = $email->getSubject();
      } else {
        continue;
      }

      if ($email->getAttachment() != null) {
        if (file_exists($email->getAttachment()) && is_readable($email->getAttachment())) {
          $filename = $this->_getCleanFileName(substr(strrchr($email->getAttachment()), 1));
          $phpMailer->AddAttachment($email->getAttachment(), $filename);
        } else {
          continue;
        }
      }

      $message = $email->getMessage();
      if (!is_array($message)) {
        $message = array();
      }

      $template = 'global/emails/' . $email->getTemplateFile();
      try {
        $message = $this->_getEmailHeader() . get_partial($template, $message) . $this->_getEmailFooter($email->getEmailTo());
        $message = $this->_convertEmailBody($message);
        $phpMailer->Body = $message;
      } catch (Exception $e) {
        continue;
      }

      if ($email->getContentType() == self::CONTENT_TYPE_HTML) {
        $phpMailer->IsHTML(true);
      } elseif($email->getContentType() == self::CONTENT_TYPE_PLAIN) {
        $phpMailer->IsHTML(false);
      }

      $phpMailer->AddCustomHeader('System-ID:' . $email->getId());

      try {
        if(!$phpMailer->Send()) {
          $sendSuccess = false;
        }
      } catch (Exception $e) {
        $sendSuccess = false;
      }

      if($sendSuccess) {
        $email->setStatus(self::STATUS_SENT);
        $email->setSentAt(date('Y-m-d H:i:s'));
        $email->setRetryCount(null);
        $email->setNotes(null);
        $email->save();
      } else {
        $email->setRetryCount($email->getRetryCount() + 1);
        if (trim($phpMailer->ErrorInfo)) {
          $email->setNotes($phpMailer->ErrorInfo);
        }
        if ($email->getRetryCount() >= sfConfig::get('app_email_max_retries')) {
          $email->setStatus(self::STATUS_FAILED);
        }
        $email->save();
      }
    }
  }

  private function _getCleanFileName($filename) {
    $filename = trim($filename);
    $removeChars  = array('([\40])', '([^a-zA-Z0-9-])', '(-{2,})');
    $replaceWith = array('-', '', '-');
    return preg_replace($removeChars, $replaceWith, $filename);
  }

  private function _getEmailHeader() {
    $str = '<html>
  <body style="font-family:Arial, Helvetica, sans-serif !important; margin:0 !important; padding:0 !important;">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td align="right">
          <a href="http://www.facebook.com/Supertain" target="_blank"><img src="' . sfConfig::get('app_site_url') . '/images/btn_fb.png" height="29" width="30"/></a><br />
          <font size="1"><a href="' . sfConfig::get('app_site_url') . '/signin">Account Login</a> | <a href="' . sfConfig::get('app_site_url') . '">Visit Supertain.com</a></font>
        <td>
      </tr>
      <tr>
        <td><a href="' . sfConfig::get('app_site_url') . '"><img alt="Supertain" title="Supertain" src="' . sfConfig::get('app_site_url') . '/images/logo_supertainme_white.jpg" height="62" width="166"/></a></td>
      </tr>
      <tr>
        <td><table width="100%" border="0" cellspacing="0" cellpadding="15">
            <tr>
              <td>';
    return $str;
  }

  private function _getEmailFooter($emailTo) {
    $str = '<br /><p>The Supertain Team</p>
              <p>&nbsp;</p>
              <p>
              <font size="1" color="#aaaaaa">
                &copy; 2012 SUPERTAIN All rights reserved.<br />
                This message was intended for ' . $emailTo . '. To UNSUBSCRIBE click <a href="' . sfConfig::get('app_site_url') . '">here</a>. For more information, please read our ANTI-SPAM/Privacy Policy, or contact us at <a href="mailto:info@supertain.com">info@Supertain.com</a>.<br /><br />
                For the more news and offers check us out at:
              </font><br /><br />
              <a href="http://www.facebook.com/Supertain" target="_blank"><img src="' . sfConfig::get('app_site_url') . '/images/btn_fb.png" height="29" width="30"/></a>&nbsp;&nbsp;&nbsp;
              <a href="http://www.twitter.com/SupertainMe" target="_blank"><img src="' . sfConfig::get('app_site_url') . '/images/btn_twitter.png" height="30" width="30"/></a>
              </p>
            </td>
            </tr>
          </table></td>
      </tr>
    </table>
  </body>
</html>';
    return $str;
  }

  private function _convertEmailBody($body) {
    $body = html_entity_decode($body);
    $body = str_replace('<p', '<p style="color:#333 !important;"', $body);
    $body = str_replace('<h2', '<h2 style="color:#39C !important;"', $body);
    $body = str_replace('<a', '<a style="color:#39C !important;"', $body);
    return $body;
  }
}
?>